<?php

class installWidgetTask extends sfBaseTask
{
  protected function configure()
  {

    $this->addOptions(array(
      new sfCommandOption('user', null, sfCommandOption::PARAMETER_REQUIRED, 'The user name'),
      new sfCommandOption('widget', null, sfCommandOption::PARAMETER_REQUIRED, 'The widget name')
    ));

    $this->namespace        = 'wixet';
    $this->name             = 'install-widget';
    $this->briefDescription = 'Install a widget to an user';
    
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $users = Doctrine::getTable('sfGuardUser');
	$users = $users->findByDql('username = ?', $options['user']);
	$user = $users->getFirst();
	
	$widgets = Doctrine::getTable('Widget');
	$widgets = $widgets->findByDql('name = ?', $options['widget']);
	$widget = $widgets->getFirst();
	
	$position = new WidgetPosition();
	if(is_object($widget))
    {
		$positions = Doctrine::getTable('WidgetPosition');
		$positions = $positions->findByDql('user_id = ? AND column_position = 1', $user->getId());
		$rowPosition = $positions->count();
		//$this->log("Position es ".$rowPosition);
		$position->setRowPosition($rowPosition);
		
		$position->setUserId($user->getId());
		$position->setWidgetId($widget->getWidgetId());
		$position->save();
    
    	//$this->log("Widget installed");
	}
	else{
		if(!is_object($user))
			throw new Exception('User "'.$options['user'].'" does not exist');
			
		throw new Exception('Widget "'.$options['widget'].'" does not exist');
	}
		
	
	

  }
}
